import React from 'react';
import util from 'util';
import {Button, Table, Modal, Tabs,message} from 'antd';
import {SearchDemo, RightButton, ColsEdit} from 'kpl';
import sys_dict from "sys_dict";
const confirm = Modal.confirm;

class A101 extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            tblSource: [],
            searchParams: {
                rolename: "",
                roletype: "",
                descript: "",
                "page": 1,
                "rows": sys_dict.defaultPageSize.toString()
            },
            totalCount: 0,
            isLoading: false,
            ylData: [],
            xzData:[],
        }
        this.userclickrecord = {};

    }
    
    //默认查询
    componentDidMount() {
        util.httpRequest({
            type: "POST", url: 'manage020008.json', params: {},
            success: function (result) {
                //console.log("manage020008.json-->", result);
                let arr = [];
                result.group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.group_id;
                    obj.itemval = i.group_name;
                    arr.push(obj);
                });
                this.setState({ylData: arr});
            }.bind(this),
            complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
        let params = this.state.searchParams;
        this.refresh(params);
    }
    
    onChange(page) {
        console.log(page);
        var params = this.state.searchParams;
        params.page = page;
        this.setState({searchParams: params});
        this.refresh(params);
    }
    
    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        var params = this.state.searchParams;
        params.rows = pageSize;
        params.page = current;
        this.setState({searchParams: params});
        this.refresh(params);
    }

    selectFun(value){
        this.userclickrecord.group_id = "";
        this.userclickrecord.sub_group_id = "";

        console.log("value:",value);
        util.httpRequest({
            type: "POST", url: 'manage020011.json', params: {group_id: value},
            success: function (result) {
                console.log("manage020011.json-->", result);
                let arr = [];
                result.sub_group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.sub_group_id;
                    obj.itemval = i.sub_group_name;
                    arr.push(obj);
                });
                this.setState({
                    xzData : arr,
                });
                var {setFieldsValue} = this.refs.form.getForm();
                var subname = "";
                subname = arr.length>0?arr[0].itemval:"";
                setFieldsValue({group_name:value,sub_group_name:subname});
            }.bind(this)
        });
    }

    selectsearchFun(value){
        util.httpRequest({
            type: "POST", url: 'manage020011.json', params: {group_id: value},
            success: function (result) {
                console.log("manage020011.json-->", result);
                let arr = [];
                result.sub_group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.sub_group_id;
                    obj.itemval = i.sub_group_name;
                    arr.push(obj);
                });
                this.setState({
                    xzData : arr,
                });
            }.bind(this)
        });
    }

    //缺少id
    loadsubFun(value,subvalue,groupid,subgroupid){
        util.httpRequest({
            type: "POST", url: 'manage020011.json', params: {group_id: groupid},
            success: function (result) {
                console.log("manage020011.json-->", result);
                let arr = [];
                result.sub_group_list.forEach(function (i) {
                    var obj = {};
                    obj.itemkey = i.sub_group_id;
                    obj.itemval = i.sub_group_name;
                    arr.push(obj);
                });
                this.setState({
                    xzData : arr,
                });
                var {setFieldsValue} = this.refs.form.getForm();
                setFieldsValue({group_name:value,sub_group_name:subvalue});
            }.bind(this)
        });
    }
    
   getTableConfig(){
    	
    	const pagination = {
            total: this.state.totalCount,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
            onShowSizeChange: this.onShowSizeChange.bind(this),
            onChange: this.onChange.bind(this)
        };
    	
        let tableConfig={};
    	tableConfig.queryConfig={
            searchTitle: "用户信息查询",
            searchInit: {
               
            },
            searchField: [
                [
                    {propsname: "员工姓名：", propsKey: "employee_name", propsType: "input", key: "1111"},
                    {propsname: "手机号：", propsKey: "phone", propsType: "input", key: "2222"},
					{propsname: "员工工号：",propsKey: "employee_no",propsType: "input",key: "4444"}
                ],
                [
                    {propsname: "所属团队", propsKey: "group_name",propsType: "select",key: "6666",optionData: this.state.ylData,selectFun:this.selectsearchFun.bind(this)},
                    {propsname: "所属小组", propsKey: "sub_group_name",propsType: "select",key:"5555",optionData: this.state.xzData},
                    {propsname: "员工状态：", propsKey: "status", propsType: "select", key: "7777",optionData:[{itemkey:"0",itemval:"启用"},{itemkey:"1",itemval:"停用"}]},
                    {propsname: "员工是否登录：", propsKey: "if_join", propsType: "select", key: "8888",optionData:[{itemkey:"0",itemval:"登录过"},{itemkey:"1",itemval:"未登录"}]},
                    {propsname: "员工是否参赛：", propsKey: "if_entry", propsType: "select", key: "9999",optionData:[{itemkey:"0",itemval:"参赛"},{itemkey:"1",itemval:"未参赛"}]}
                ]
            ]
        };
    	
    	tableConfig.resultConfig={
                pagination: pagination,
                loading: this.state.isLoading,
                dataSource: this.state.tblSource,
                columns: [{
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    render: function (value, data, rowIndex) {
                        return rowIndex+1;
                    }
                }, {
                    title: '工号',
                    dataIndex: 'employee_no',
                    key: 'employee_no'
                }, {
                    title: '员工姓名',
                    dataIndex: 'employee_name',
                    key: 'employee_name'
                }, {
                    title: '手机号',
                    dataIndex: 'phone',
                    key: 'phone'
                }, {
                    title: '所属团队',
                    dataIndex: 'group_name',
                    key: 'group_name',
                }, {
                    title: '所属小组',
                    dataIndex: 'sub_group_name',
                    key: 'sub_group_name',
                },
                {
                    title: '是否参赛',
                    dataIndex: 'if_entry',
                    key: 'if_entry',
                    render: (text, data, index) => (
                        <span>{data.if_entry == "1" ?
                            <p>否</p> :
                            <p>是</p>
                        }
                        </span>
                    )
                },
                    {
                        title: '是否登录过',
                        dataIndex: 'if_join',
                        key: 'if_join',
                        render: (text, data, index) => (
                            <span>{data.if_join == "1" ?
                                <p>未登录</p>:
                                <p>登录过</p>
                            }
                    </span>
                        )
                    },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (text, data, index) => (
                        <span>{data.status == "1" ?
                            <a onClick={this.row_modifyStatus.bind(this, data, "1")}>停用</a> :
                            <a onClick={this.row_modifyStatus.bind(this, data, "0")}>启用</a>}
                        </span>
                    )
                },{
                    title: '操作',
                     render: (text, data, index) => (
                        <span>
                                <Button key="back" type="ghost" size="small"
                                    onClick={this.edit.bind(this,data, index)}>修改</Button>
                                 
                        </span>
                        )
                }]
            };
    	return tableConfig;
   }

    refresh(paramdic) {
        this.setState({isLoading: true});
        util.httpRequest({
            type: "POST", url: 'manage020004.json', params: paramdic, plattype: '', success: function (result) {
                if (result.ret_code == "0000") {
                    this.setState({
                        tblSource: result.employee_list,
                        totalCount: result.counts
                    });
                }
            }.bind(this),
            complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
    }

    search(params) {
        console.log("searchparams:",params);
        params.page = "1";
        params.rows = sys_dict.defaultPageSize.toString();
        this.setState({
            searchParams: params
        });
        this.refresh(params);
    }

    row_modifyStatus(record, type) {
        var me = this;
        if (type == "0") {
        	 record.status="0";
            var sContent="若将员工:["+record.employee_name+"] 状态改为禁用则该员工不再参与排行。无法再登录app,确认要禁用该员工吗？";
	        var sOkText="确认停用";
	        var sCancelText="不停用";
        } else{
        	record.status="1";
        	var sContent="确认要将员工:["+record.employee_name+"]由禁用状态改为正常吗？";
	        var sOkText="确认启用";
	        var sCancelText="不启用";
        }
        
        Modal.confirm({
                title:sOkText,
                content: sContent,
                okText: sOkText,
                cancelText: sCancelText,
                onOk: function () {                  
                    util.httpRequest({
                        type: "POST",
                        url: 'manage020002.json',
                        params: {
                            user_id: record.user_id,
                            status: record.status=='0'?'1':'0'
                        },
                        success: function (result) {
                            me.refresh(me.searchParams);
                        }.bind(this)
                    });
                }
            });
    }


	row_deleteRecord(record, type, e) {
		var me = this;
        var sContent="若将员工:["+record.employee_name+"] 删除则该员工不再参与排行。无法再登录app,确认要禁用该员工吗？";
        var sOkText="确认删除";
        var sCancelText="不删除";
        
        
        Modal.confirm({
            title:sOkText,
                content: sContent,
                okText: sOkText,
                cancelText: sCancelText,
                onOk: function () {                  
                    util.httpRequest({
                        type: "POST",
                        url: 'manage020003.json',
                        plattype: '',
                        params: record,
                        success: function (result) {
                            me.refresh(me.state.searchParams);
                        }.bind(this)
                    });
                }
            });
	}

    edit(record, index) {
        console.log("recofdd:::",record);
        this.setState({
            operateData: record,
            modalV: true,
            operateType: 'EDIT',
            modalTitle: "修改"
        }, function () {
            var {setFieldsValue} = this.refs.form.getForm();
            setFieldsValue(record);
            this.userclickrecord = record;
            console.log("this.userclickrecord"+this.userclickrecord);
            this.loadsubFun(record.group_name,record.sub_group_name,record.group_id,record.sub_group_id);
        });
    }

    getAddFormConfig(){
    	const createConfig = {
            operateTitle: "员工文件上传：请从本地选择后缀为.xls或者.xlsx的员工信息文件上传",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 12, wrapperCol: 12},
            operateField: [
                 [
                    {
                        propsname: "选择员工信息文件：",
                        propsKey: "content",
                        propsType: "fileupload",
                        uploadCustomProps:{accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},
                        key: "333",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ]
            ]
        };
        return createConfig;
   }

    ///修改员工model框
    messageChange(){
        const createConfig = {
            operateTitle: "修改员工信息",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {title: "", busi_type: "", use_status: "", content: ""},
            operateColSm: 24,
            operateCol: {labelCol: 6, wrapperCol: 18},
            operateField: [
                [{
                    propsname: "工号：", propsKey: "employee_no", propsType: "input", key: "111", editDisable: true
                }],
                [{
                    propsname: "姓名：", propsKey: "employee_name", propsType: "input", key: "111"
                }],
                [{
                    propsname: "手机号：", propsKey: "phone", propsType: "input", key: "112"
                }],
                [{
                    propsname: "是否参赛：", propsKey: "if_entry", propsType: "select",key: "116",optionData:[{itemkey:"0",itemval:"是"},{itemkey:"1",itemval:"否"}]
                }],
                [{
                    propsname: "状态：", propsKey: "status", propsType: "select", key: "113",optionData:[{itemkey:"0",itemval:"启用"},{itemkey:"1",itemval:"停用"}], editDisable: true
                }],
                [{
                    propsname: "所属团队：", propsKey: "group_name", propsType: "select", key: "114",optionData: this.state.ylData,selectFun:this.selectFun.bind(this)
                }],
                [{
                    propsname: "所属小组：", propsKey: "sub_group_name", propsType: "select", key: "115",optionData: this.state.xzData
                }]
            ]
        };
        return createConfig;
    }

    changeSave(value) {
        var form = this.refs.form.getForm();
        var messageData = this.state.operateData;
        form.validateFields((errors, values) => {
            if (!!errors) {
                return;
            }
            console.log("================");
            console.log(values.group_name);
            console.log(values.sub_group_name);
            console.log(this.userclickrecord.group_id);
            console.log(this.userclickrecord.sub_group_id);
            console.log("================");

            // 关闭弹出框,修改员工信息接口不完善
            util.httpRequest({
                type: "POST", url: 'manage020013.json', params: {
                    user_id: messageData.user_id,
                    phone:values.phone,
                    employee_name:values.employee_name,
                    if_entry: values.if_entry,
                    //这两个id取不到值，需要修改
                    group_id:this.userclickrecord.group_id==""?values.group_name:this.userclickrecord.group_id,
                    sub_group_id:this.userclickrecord.sub_group_id==""?values.sub_group_name:this.userclickrecord.sub_group_id,
                    if_move_step:"1",
                },
                success: function (result) {
                    let params = this.state.searchParams;
                    this.refresh(params);
                    this.setState({
                        modalV: false
                    });
                }.bind(this)
            });
        });
        console.log("value:", value);
    }

    handleCancel() {
        this.setState({
            modalV: false,
            modalVisible: false,
            modalDetailVisible: false
        });
    }   
    add_display() {
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            operateData: {},
            modalTitle: "新增"
        }, function () {
            var form = this.refs.addForm.getForm();
            form.resetFields();
        });
    }

    add_save(values) {
        var form = this.refs.addForm.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
            	 this.handleCancel();
                return;
            }
           if (values.content != undefined && values.content != "") {
                    var obj = {};
                    obj.file_name = values.content[0].response.file_name;
                    obj.resource_id = values.content[0].response.resource_id;
                    
           } else{           	
           		message.error("请先选择文件上传");
           		this.handleCancel();
           		return;
           }
           util.httpRequest({
                        type: "POST",
                        url: 'manage020001.json',
                        plattype: '',
                        params: obj,
                        success: function (result) {
                            if(result.ret_code=="0000"){
                            		message.success("处理成功");
                            		this.handleCancel();
                            		this.componentDidMount();
                            	}else{
                            		message.error("处理失败");
                            	}
                        }.bind(this)
                    });
           
        });
    }

    render() {
        let tableConfig = this.getTableConfig();
        let addFormConfig =this.getAddFormConfig();
        let messageChange =this.messageChange();
        
        return (
            <div>
                <SearchDemo search={this.search.bind(this)} searchConfig={tableConfig.queryConfig}></SearchDemo>
                <RightButton styleName="addBtn" propsKey="121" btnTxt="+  导入员工    " oprate={this.add_display.bind(this)}> </RightButton>
                <Table {...tableConfig.resultConfig}></Table>
                <Modal visible={this.state.modalVisible} title={addFormConfig.operateTitle} width="50%"
                               closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.add_save.bind(this)}>确定上传</Button>
                        ]}>
                			<ColsEdit ref="addForm" key={Math.random()}  config={addFormConfig}></ColsEdit>
                </Modal>
                <Modal visible={this.state.modalV} title={messageChange.operateTitle}
                       closable={false} footer={[
                            <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                            <Button key="submit" type="primary" size="large"
                                    onClick={this.changeSave.bind(this)}>确定修改</Button>
                        ]}>
                    <ColsEdit ref="form"  key={Math.random()}  config={messageChange}></ColsEdit>
                </Modal>
            </div>
        );
    }
}

export default A101;